package com.tt.fashionWebSite.dao.jpa;

import com.tt.fashionWebSite.dao.HinhAnhSanPhamDao;
import com.tt.fashionWebSite.domain.HinhAnhSanPham;
import com.tt.fashionWebSite.dto.HinhAnhSanPhamDto;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by PC on 11/28/14.
 */
@Repository("hinhAnhSanPham")
public class HinhAnhSanPhamJpaDao extends GenericJpaDao<HinhAnhSanPham,String> implements HinhAnhSanPhamDao {
    public HinhAnhSanPhamJpaDao(){
        super(HinhAnhSanPham.class);
    }

    @Override
    public List<HinhAnhSanPhamDto> getImageByProduct(String maCTSP) {
        String strQuery = "SELECT "
              + "s.MA_HINH_SP, "
              + "s.TEN_HINH "
              + "FROM hinh_anh_sp s "
              + "WHERE s.MA_CT_SP = :maCTSP ";

        Query query = getEntityManager().createNativeQuery(strQuery);
        query.setParameter("maCTSP", maCTSP);

        List<Object> results = query.getResultList();
        List<HinhAnhSanPhamDto> hinhAnhSanPhamDtos = new ArrayList<HinhAnhSanPhamDto>();
        HinhAnhSanPhamDto hinhAnhSanPhamDto = null;
        for (int i = 0; i < results.size(); i++) {
            Object[] userDB = (Object[]) results.get(i);
            hinhAnhSanPhamDto = new HinhAnhSanPhamDto(userDB);
            hinhAnhSanPhamDtos.add(hinhAnhSanPhamDto);
        }
        return hinhAnhSanPhamDtos;
    }

    @Override
    public void deletePicture(String maCTSP) {
        Query q1 = getEntityManager().createQuery("DELETE FROM HinhAnhSanPham c WHERE c.chiTietSanPham.maCTSP = :maCTSP ");
        q1.setParameter("maCTSP", maCTSP);
        q1.executeUpdate();
    }
}
